package com.chineseall.app;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.CloseReason;
import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chineseall.app.ws.WebSocketEndpoint;
import com.chineseall.rebirth.api.helper.Const;
import com.google.common.collect.Maps;

public class ConnectionManager {

    public static final ConnectionManager INSTANCE = new ConnectionManager();

    private final ConcurrentMap<Integer, WebSocketEndpoint> uids = Maps.newConcurrentMap();

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public final AtomicInteger NO = new AtomicInteger(0);
    public final AtomicInteger max = new AtomicInteger(0);

    public boolean add(int uid, WebSocketEndpoint ws) {
        if (uid < 1)
            return false;
        WebSocketEndpoint ws2 = uids.put(uid, ws);
        if (ws2 != null && ws2.session != null && ws2.session.isOpen()) {
            logger.info("uid is exist ws={},ws2={}", ws, ws2);
            if (Const.IS_PRODUCTION)
                close(ws2.session, new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "is exist"));
            return false;
        } else {
            if (max.get() < uids.size())
                max.incrementAndGet();
        }
        return true;
    }

    public WebSocketEndpoint getSession(int uid) {
        return uids.get(uid);
    }

    /**
     * 当前登陆用户
     * 2013-12-20 
     * @return
     */
    public Collection<WebSocketEndpoint> getConnections() {
        return uids.values();
    }

    public Session getSession(String sessionId) {
        Set<Session> openSessions = getOpenSessions();
        for (Session s : openSessions) {
            if (s.getId().equals(sessionId))
                return s;
        }
        return null;
    }

    /***
     * 当前所有连接
     * 2013-12-20 
     * @return
     */
    public Set<Session> getOpenSessions() {
        Iterator<Entry<Integer, WebSocketEndpoint>> it = uids.entrySet().iterator();
        if (it.hasNext())
            return it.next().getValue().session.getOpenSessions();
        return Collections.emptySet();
    }

    public Map<String, Object> stats() {
        Map<String, Object> stat = Maps.newHashMap();
        stat.put("users", uids.size());
        stat.put("no", NO.get());
        stat.put("max", max.get());
        stat.put("session", getOpenSessions().size());
        return stat;
    }

    public void remove(WebSocketEndpoint websocket) {
        if (websocket == null) {
            logger.warn("close websocket is null");
            return;
        }
        if (websocket.getUid() > 0)
            uids.remove(websocket.getUid());

    }

    public void close(Session session, CloseReason reason) {
        try {
            session.close(reason);
        } catch (Exception e) {
            logger.error("colsed {}", e);
        }
    }

}
